﻿#include "dbtools.h"


QSqlQuery* dbtools::CreatConnection()
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");//建库
    db.setDatabaseName("mymusic.db");//给数据库起名字
    if(!db.open())
    {
        return NULL;
    }
    query = new QSqlQuery(db);
    if(!query->exec(QString("create table LocalMusic (FileName varchar,MusicName varchar,primary key(FileName,MusicName))")))//本地音乐列表数据，把歌曲名和歌曲路径给存起来
    {
        qDebug()<<"创建表失败"<<query->lastError().text();
    }
    return query;
}

bool dbtools::ReadList(QListWidget *qw,QMediaPlaylist *PlayList)
{
    //读取音乐列表
    qw->clear();    //添加列表之前先清除一遍
    query->exec("select * from LocalMusic");
    QSqlRecord rec = query->record();
    qDebug() << QObject::tr("LocalMusic" ) << rec.count();
    while(query->next())
    {
        QStringList list;
        list<<query->value(1).toString();
        qw->addItems(list); //在ListWidget控件的第行0插入一个列表list内容
        //qDebug()<<query->value(0).toString();
        PlayList->addMedia(QMediaContent(QUrl(query->value(0).toString())));   //添加文件到播放列表对象
    }
    //读取结束
    return true;
}

bool dbtools::addFiles(std::vector<QString> musiclist_v,QMediaPlaylist *PlayList,QString musicFiles)
{
    for(std::vector<QString >::iterator iter = musiclist_v.begin();iter != musiclist_v.end();++iter)
    {
        if(iter[0].indexOf(".mp3") != -1)    //非mp3不加入
        {
             PlayList->addMedia(QMediaContent(QUrl(iter[0])));   //添加文件到播放列表对象
            if(!query->exec(QString("insert into LocalMusic values('%1','%2')").arg(iter[0]).arg(iter[0].replace(musicFiles+"/",""))))
            {
                 qDebug()<<"链接失败"<<query->lastError().text();
            }
        }
    }
}
